package com.lx.handler;

import com.lx.stereotype.Handler;

import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import static org.springframework.web.reactive.function.server.ServerResponse.ok;

/**
 * 处理时间的方法
 *
 * @author 段誉
 * @create 2019-05-15 13:18
 */
@Handler
public class TimeHandler {
  /**
   * @desc 获取当前时间
   * @Author 段誉
   * @Date 2019/5/15 13:22
   * @method
   */
  public Mono<ServerResponse> getTime(ServerRequest serverRequest) {
    return ok().contentType(MediaType.TEXT_PLAIN)
            .body(Mono.just("Now is " + new SimpleDateFormat("HH:mm:ss").format(new Date())),
                    String.class);
  }

  /**
   * @desc 获取当前日期
   * @Author 段誉
   * @Date 2019/5/15 13:23
   * @method
   */
  public Mono<ServerResponse> getDate(ServerRequest serverRequest) {
    return ok().contentType(MediaType.TEXT_PLAIN)
            .body(Mono.just("Today is " + new SimpleDateFormat("yyyy-MM-dd")
                    .format(new Date())),
                    String.class);
  }
  
  /**
   * @desc 主动推送
   * MediaType.TEXT_EVENT_STREAM表示Content-Type为text/event-stream，即SSE，服务器推送事件
   * 利用interval生成每秒一个数据的流
   * @Author 段誉
   * @Date 2019/5/15 14:04
   * @method 
   */
  public Mono<ServerResponse> sendTimePerSec(ServerRequest serverRequest) {
    return ok().contentType(MediaType.TEXT_EVENT_STREAM)
            .body(Flux.interval(Duration.ofSeconds(1))
                    .map(l -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                            .format(new Date())), String.class);
  }
}
